"""
邮件服务模块
"""
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.utils import formataddr
from typing import Optional, List
import jinja2
import os

from core.config import settings
from core.logging_config import get_logger
from datetime import datetime

logger = get_logger("email_service")


class EmailService:
    """邮件服务类"""
    
    def __init__(self):
        self.smtp_server = settings.smtp_server
        self.smtp_port = settings.smtp_port
        self.smtp_username = settings.smtp_username
        self.smtp_password = settings.smtp_password
        
        # 模板配置
        self.template_dir = os.path.join(os.path.dirname(__file__), "..", "templates", "email")
        self.jinja_env = jinja2.Environment(
            loader=jinja2.FileSystemLoader(self.template_dir),
            autoescape=True
        )
    
    def send_email(
        self,
        to_emails: List[str],
        subject: str,
        content: str,
        is_html: bool = False,
        cc_emails: List[str] = None,
        bcc_emails: List[str] = None
    ) -> bool:
        """发送邮件"""
        try:
            # 创建邮件消息
            if is_html:
                msg = MIMEText(content, 'html', 'utf-8')
            else:
                msg = MIMEText(content, 'plain', 'utf-8')
            
            msg['Subject'] = subject
            msg['From'] = formataddr((settings.app_name, self.smtp_username))
            msg['To'] = ', '.join(to_emails)
            
            if cc_emails:
                msg['Cc'] = ', '.join(cc_emails)
            
            if bcc_emails:
                msg['Bcc'] = ', '.join(bcc_emails)
            
            # 发送邮件
            with smtplib.SMTP(self.smtp_server, self.smtp_port) as server:
                server.starttls()
                server.login(self.smtp_username, self.smtp_password)
                
                recipients = to_emails[:]
                if cc_emails:
                    recipients.extend(cc_emails)
                if bcc_emails:
                    recipients.extend(bcc_emails)
                
                server.sendmail(self.smtp_username, recipients, msg.as_string())
            
            logger.info(f"邮件发送成功: {subject} -> {to_emails}")
            return True
            
        except Exception as e:
            logger.error(f"邮件发送失败: {e}")
            return False
    
    def send_template_email(
        self,
        to_emails: List[str],
        subject: str,
        template_name: str,
        template_data: dict,
        cc_emails: List[str] = None,
        bcc_emails: List[str] = None
    ) -> bool:
        """发送模板邮件"""
        try:
            # 渲染模板
            template = self.jinja_env.get_template(f"{template_name}.html")
            content = template.render(**template_data)
            
            # 发送邮件
            return self.send_email(
                to_emails=to_emails,
                subject=subject,
                content=content,
                is_html=True,
                cc_emails=cc_emails,
                bcc_emails=bcc_emails
            )
            
        except Exception as e:
            logger.error(f"模板邮件发送失败: {e}")
            return False
    
    def send_password_reset_email(self, to_email: str, reset_token: str, username: str) -> bool:
        """发送密码重置邮件"""
        try:
            reset_url = f"{settings.app_url}/reset-password?token={reset_token}"
            
            template_data = {
                "username": username,
                "reset_url": reset_url,
                "app_name": settings.app_name,
                "support_email": self.smtp_username
            }
            
            subject = f"[{settings.app_name}] 密码重置请求"
            
            return self.send_template_email(
                to_emails=[to_email],
                subject=subject,
                template_name="password_reset",
                template_data=template_data
            )
            
        except Exception as e:
            logger.error(f"密码重置邮件发送失败: {e}")
            return False
    
    def send_welcome_email(self, to_email: str, username: str, temporary_password: str = None) -> bool:
        """发送欢迎邮件"""
        try:
            template_data = {
                "username": username,
                "app_name": settings.app_name,
                "login_url": f"{settings.app_url}/login",
                "temporary_password": temporary_password,
                "support_email": self.smtp_username
            }
            
            subject = f"欢迎使用 {settings.app_name}"
            
            return self.send_template_email(
                to_emails=[to_email],
                subject=subject,
                template_name="welcome",
                template_data=template_data
            )
            
        except Exception as e:
            logger.error(f"欢迎邮件发送失败: {e}")
            return False
    
    def send_account_lock_email(self, to_email: str, username: str) -> bool:
        """发送账户锁定通知邮件"""
        try:
            template_data = {
                "username": username,
                "app_name": settings.app_name,
                "support_email": self.smtp_username
            }
            
            subject = f"[{settings.app_name}] 账户安全通知"
            
            return self.send_template_email(
                to_emails=[to_email],
                subject=subject,
                template_name="account_locked",
                template_data=template_data
            )
            
        except Exception as e:
            logger.error(f"账户锁定邮件发送失败: {e}")
            return False
    
    def send_system_notification(
        self,
        to_emails: List[str],
        title: str,
        message: str,
        notification_type: str = "info"
    ) -> bool:
        """发送系统通知邮件"""
        try:
            template_data = {
                "title": title,
                "message": message,
                "notification_type": notification_type,
                "app_name": settings.app_name,
                "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            }
            
            subject = f"[{settings.app_name}] {title}"
            
            return self.send_template_email(
                to_emails=to_emails,
                subject=subject,
                template_name="system_notification",
                template_data=template_data
            )
            
        except Exception as e:
            logger.error(f"系统通知邮件发送失败: {e}")
            return False
    
    def test_smtp_connection(self) -> bool:
        """测试SMTP连接"""
        try:
            with smtplib.SMTP(self.smtp_server, self.smtp_port) as server:
                server.starttls()
                server.login(self.smtp_username, self.smtp_password)
            logger.info("SMTP连接测试成功")
            return True
        except Exception as e:
            logger.error(f"SMTP连接测试失败: {e}")
            return False


# 全局邮件服务实例
email_service = EmailService()


# 便捷函数
def send_password_reset_email(to_email: str, reset_token: str, username: str) -> bool:
    """发送密码重置邮件的便捷函数"""
    return email_service.send_password_reset_email(to_email, reset_token, username)


def send_welcome_email(to_email: str, username: str, temporary_password: str = None) -> bool:
    """发送欢迎邮件的便捷函数"""
    return email_service.send_welcome_email(to_email, username, temporary_password)


def send_system_notification(
    to_emails: List[str],
    title: str,
    message: str,
    notification_type: str = "info"
) -> bool:
    """发送系统通知邮件的便捷函数"""
    return email_service.send_system_notification(to_emails, title, message, notification_type)